package IO;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Vector;

import data.Show;

public class Save 
{
	
	public static void saveShows()
	{
		//Save.saveShows(showList,"shows");
		Save.saveShows("showsXML");
	}
	public static void saveShows(String file)
	{
		//Save.saveShows(showList,"shows");
		if (!Read.isShowListNull())
		{
			Save.saveShowsToXML(Read.readShows(), file);
		}
		Read.closeShowList();
	}
	
//	public static void saveShows(Vector<Show> showList, String fileName)
//	{
//		
//		String showsFile = SystemInfo.getApplicationDirectory() + fileName + ".ssf";//*.ssf = Show Storage File
//		
//		File file = new File(showsFile);
//		if(!file.exists())
//		{
//			try {
//				file.createNewFile();
//			} catch (IOException e) 
//			{
//				System.err.println("Cannot create file");
//			}
//		}
//		
//		FileOutputStream fos = null;
//		try {
//			fos = new FileOutputStream (showsFile);
//		} catch (FileNotFoundException e) {
//			// TODO Auto-generated catch block
//			System.err.println("Cannot open " + showsFile);
//		}
//
//		ObjectOutputStream oos;
//		if(fos != null)
//		{
//			try 
//			{
//				oos = new ObjectOutputStream(fos);
//				oos.writeObject(showList);
//				fos.close();
//			} 
//			catch (IOException e) 
//			{
//				// TODO Auto-generated catch block
//				System.err.println("Cannot write to "+showsFile);
//			}
//		}
//
//	}
	
	public static void saveShowsToXML(Vector<Show> showList)
	{
		Save.saveShowsToXML(showList, "showsXML");
	}
	public static void saveShowsToXML(Vector<Show> showList, String filename)
	{
		String showsXMLFile = SystemInfo.getApplicationDirectory() + filename + ".xml";
		
		File file = new File(showsXMLFile);
		if(!file.exists())
		{
			try
			{
				file.createNewFile();
			}
			catch(Exception e)
			{
				Log.printErrorln("Unable to create file");
			}
		}
		file = null;
		
		String xml = "<?xml version=\"1.0\"?>\n"; 
		xml +="<sonny>\n"; 
		for(Show s : showList)
		{
			xml+=s.toXML("\t");
		}
		xml +="</sonny>";
		try
		{
			//xml = java.net.URLDecoder.decode(xml, "UTF-8");
			BufferedWriter out = new BufferedWriter(new FileWriter(showsXMLFile));
			out.write(xml);
			out.close();
			out = null;
		}
		catch(Exception e)
		{
			Log.printErrorln("Unable to write to file "+showsXMLFile);
		}
		
	}
}
